package com.cqc.listviewchoicedemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${cqc} on 2017/3/13.
 *
 */

public class OSMultipleModalChoiceActivity extends AppCompatActivity {

    private static final String TAG = "OSMultipleModal";
    private ListView listView;
    private Button btn;
    private List<String> dataList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_os_multiple_modal_choice);
        initData();
        findViews();
        initViews();
    }

    private void initData() {
        for (int i = 0; i < 100; i++) {
            dataList.add("item" + i);
        }
    }

    private void initViews() {
        //设置长按多选模式也有2种方法：xml和java设置
//        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(OSMultipleModalChoiceActivity.this, android.R.layout.simple_list_item_multiple_choice, dataList);
        listView.setAdapter(adapter);
        MyMultiChoiceModeListener listener = new MyMultiChoiceModeListener();
        listView.setMultiChoiceModeListener(listener);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String text = (String) listView.getItemAtPosition(position);
                Log.d(TAG, "text=" + text);
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                long[] checkItemIds = listView.getCheckItemIds();
                StringBuffer sb1 = new StringBuffer();
                for (int i = 0; i < checkItemIds.length; i++) {
                    sb1.append(checkItemIds[i]+",");
                }
                Log.d(TAG, "选中的position集合是：sb1 =" + sb1.toString());
            }
        });
    }

    private void findViews() {
        listView = (ListView) findViewById(R.id.listView);
        btn = (Button) findViewById(R.id.btn);
    }

}
